<template>
  <div class="map_container">
    <div id="container" style="width:100vw; height:100vh"></div>
  </div>
</template>

<script>
const title =
  '方恒假日酒店<span style="font-size:11px;color:#F00;">价格:318</span>'
const content = []
content.push('电话：010-64733333')
/* eslint-disable */
import $ from 'jquery'
import _ from 'lodash'
export default {
  data() {
    return {
      map: null, // 地图对象
      carMarkers: [], // 覆盖物数组
      timer: null,
      currentZoom: 5,

      carLevelCenter: [], // 请求参数, 当前的车有哪些
      districtLevelCenter: [], // 请求参数，当前的区有哪些

      provinceData: [
        {
          id: '320000',
          name: '江苏省',
          level: 'province',
          pos: [118.767413, 32.041544],
          carNumber: '1000辆'
        }
      ],
      provinceMarkers: [],
      provinceOverlayGroups: null,

      cityData: [
        {
          id: '320100',
          name: '南京市',
          level: 'city',
          pos: [118.767413, 32.041544],
          carNumber: '1000辆'
        },
        {
          id: '321000',
          name: '扬州市',
          level: 'city',
          pos: [119.421003, 32.393159],
          carNumber: '100辆'
        }
      ],
      cityMarkers: [],
      cityOverlayGroups: null,

      districtData: [
        {
          id: '320102',
          name: '玄武区',
          level: 'district',
          pos: [118.792199, 32.050678]
        },
        {
          id: '320106',
          name: '鼓楼区',
          level: 'district',
          pos: [118.769739, 32.066966]
        }
      ],
      districtMarkers: [],
      districtOverlayGroups: null,

      infoWindow: null,
      cluster: null,
      data1: [
        {
          id: '1',
          pos: [118.799857, 32.054203]
        },
        {
          id: '2',
          pos: [118.790072, 32.056385]
        },
        {
          id: '3',
          pos: [118.803634, 32.050274]
        },
        {
          id: '4',
          pos: [118.802089, 32.050056]
        }
      ],
      data2: []
    }
  },
  // computed: {
  //   datas2() {
  //     return this.data1.map(v => {
  //       return {
  //         id: v.id,
  //         pos: [v.pos[0] - 0.01, v.pos[1] - 0.01]
  //       }
  //     })
  //   }
  // },
  mounted() {
    this.initMap()
    // this.initCarMarker()
    this.initProvinceOverlayGroups()
    // this.initCityOverlayGroups()
    this.initInfoWindow()
  },
  methods: {
    // 初始化地图对象
    initMap() {
      this.map = new AMap.Map('container', {
        center: [105, 34],
        zoom: 5,
        zooms: [5, 15],
        // zoom: 12, //设置地图显示的缩放级别
        //center: [116.43, 39.92], //设置地图中心点坐标
        viewMode: '2D', //设置地图模式
        lang: 'zh_cn' //设置地图语言类型
      })
      // this.map.plugin(['AMap.MarkerClusterer']) // 点聚合插件
      this.mountZoomEnd()
      this.mountDragend()
    },

    initInfoWindow() {
      this.infoWindow = new AMap.InfoWindow()
    },

    initProvinceOverlayGroups() {
      let PMarkers = []
      let d = this.provinceData
      for (let i = 0; i < d.length; i++) {
        let lnglat = d[i]
        const marker = this.setNumberMarker(
          lnglat.pos[0],
          lnglat.pos[1],
          lnglat.id,
          lnglat.name,
          7
        )
        PMarkers.push(marker)
      }
      this.provinceOverlayGroups = new AMap.OverlayGroup(PMarkers)
      this.map.add(this.provinceOverlayGroups)
      this.provinceMarkers = PMarkers
    },

    initCityOverlayGroups() {
      let CMarkers = []
      let d = this.cityData
      for (let i = 0; i < d.length; i++) {
        let lnglat = d[i]
        const marker = this.setNumberMarker(
          lnglat.pos[0],
          lnglat.pos[1],
          lnglat.id,
          lnglat.name,
          11
        )
        CMarkers.push(marker)
      }
      this.cityOverlayGroups = new AMap.OverlayGroup(CMarkers)
      this.map.add(this.cityOverlayGroups)
      this.cityMarkers = CMarkers
    },

    initDistrictOverlayGroups() {
      // districtData数据获取需要带上中心坐标
      let DMarkers = []
      let d = this.districtData
      for (let i = 0; i < d.length; i++) {
        let lnglat = d[i]
        const marker = this.setNumberMarker(
          lnglat.pos[0],
          lnglat.pos[1],
          lnglat.id,
          lnglat.name,
          14
        )
        DMarkers.push(marker)
      }
      this.districtOverlayGroups = new AMap.OverlayGroup(DMarkers)
      this.map.add(this.districtOverlayGroups)
      this.districtMarkers = DMarkers
    },

    mountZoomEnd() {
      // todo 待优化，暂时未找到更好的方法(clearMap貌似并不管用)
      this.map.on('zoomend', e => {
        const currentZoom = this.map.getZoom()
        this.currentZoom = currentZoom
        clearTimeout(this.timer) // 缩放时清除正在计时器中刷新的小车
        // console.log('currentZoom: ', currentZoom)
        if (currentZoom < 7) {
          // 省级
          if (this.provinceOverlayGroups === null) {
            this.initProvinceOverlayGroups()
          }
          if (this.cityOverlayGroups) {
            this.map.remove(this.cityOverlayGroups)
            this.cityOverlayGroups = null
          }
          if (this.carMarkers.length > 0) {
            this.map.remove(this.carMarkers)
            this.carMarkers = []
          }
          if (this.districtOverlayGroups) {
            this.map.remove(this.districtOverlayGroups)
            this.districtOverlayGroups = null
          }
        }
        if (currentZoom >= 7 && currentZoom < 11) {
          // 市级
          if (this.cityOverlayGroups === null) {
            this.initCityOverlayGroups()
          }
          if (this.provinceOverlayGroups) {
            this.map.remove(this.provinceOverlayGroups)
            this.provinceOverlayGroups = null
          }
          if (this.districtOverlayGroups) {
            this.map.remove(this.districtOverlayGroups)
            this.districtOverlayGroups = null
          }
          if (this.carMarkers.length > 0) {
            this.map.remove(this.carMarkers)
            this.carMarkers = []
          }
        }
        if (currentZoom >= 11 && currentZoom < 14) {
          // 区级
          this.districtLevelCenter = this.map.getCenter()
          if (this.districtOverlayGroups === null) {
            this.initDistrictOverlayGroups()
          }
          if (this.provinceOverlayGroups) {
            this.map.remove(this.provinceOverlayGroups)
            this.provinceOverlayGroups = null
          }
          if (this.cityOverlayGroups) {
            this.map.remove(this.cityOverlayGroups)
            this.cityOverlayGroups = null
          }
          if (this.carMarkers.length > 0) {
            this.map.remove(this.carMarkers)
            this.carMarkers = []
          }
        }
        if (currentZoom >= 14) {
          // 车辆级,todo,随汽车中心点进行定位信息更新，这里的逻辑待更新
          this.carLevelCenter = this.map.getCenter()
          if (this.carMarkers.length === 0) {
            this.initCarMarker()
          }
          if (this.provinceOverlayGroups) {
            this.map.remove(this.provinceOverlayGroups)
            this.provinceOverlayGroups = null
          }
          if (this.cityOverlayGroups) {
            this.map.remove(this.cityOverlayGroups)
            this.cityOverlayGroups = null
          }
          if (this.districtOverlayGroups) {
            this.map.remove(this.districtOverlayGroups)
            this.districtOverlayGroups = null
          }
        }
      })
    },

    mountDragend() {
      this.map.on('dragend', () => {
        // todo 区级别的拖拽
        if (this.currentZoom >= 11 && this.currentZoom < 14) {
          const center = this.map.getCenter()
          console.log('center: ', center)
          // 1.初始化数据
          // 2.重新设置更新
        }
        if (this.currentZoom >= 14) {
          //车辆级别拖拽
          const center = this.map.getCenter()
          console.log('center: ', center)
          const { lat, lng } = center
          // todo 这里根据中心点坐标发请求获取当前视图范围内车辆,实质是更新中心坐标，使请求里的数据每次改变
          // this.doSomethingAsync(center) 这里用到的参数是上面保存的参数
        }
      })
    },

    // 初始化汽车覆盖物
    initCarMarker() {
      // ddata1数据获取需要带上中心坐标
      let lMarkers = []
      for (let i = 0; i < this.data1.length; i++) {
        let lnglat = this.data1[i].pos
        const marker = this.setCarMarker(
          this.data1[i].pos[0],
          this.data1[i].pos[1],
          this.data1[i].id
        )
        lMarkers.push(marker)
      }
      const overlayGroups = new AMap.OverlayGroup(lMarkers)
      this.map.add(overlayGroups)
      this.carMarkers = lMarkers
      // todo 每三秒执行更新策略,这一步应该在这里的初始化里面进行
      this.fakeGetData()
    },

    // 更新覆盖物
    updateMarker() {
      // 更新已有的，删除没有的，添加新增的
      let newMarkers = []
      // 这里要先删除已经不在的
      this.deleteOldMarkers()
      for (let i = 0; i < this.data1.length; i++) {
        const alreadyMarker = this.carMarkers.find(
          v => v.B.extData.id === this.data1[i].id
        )
        if (alreadyMarker) {
          // 更新已有的
          const newlnglat = this.data1[i].pos
          alreadyMarker.moveTo(
            new AMap.LngLat(newlnglat[0], newlnglat[1]),
            5000
          )
          newMarkers.push(alreadyMarker)
        } else {
          // 添加新的
          const marker = this.setCarMarker(
            this.data1[i].pos[0],
            this.data1[i].pos[1],
            this.data1[i].id
          )
          this.map.add(marker)
          newMarkers.push(marker)
        }
      }
      this.carMarkers = newMarkers
    },

    deleteOldMarkers() {
      // 是老的marker数组
      for (let i = 0; i < this.carMarkers.length; i++) {
        const isHave = this.data1.some(
          v => v.id === this.carMarkers[i].B.extData.id
        )
        if (!isHave) {
          this.map.remove(this.carMarkers[i])
        }
      }
    },

    setNumberMarker(lng, lat, id, name, zoomLevel) {
      let marker = new AMap.Marker({
        position: new AMap.LngLat(lng, lat),
        content: `<div style="
          width:50px;
          height:50px;
          border-radius:25px;
          background-color:#0e81e5;
          font-size: 12px;
          display:flex; 
          justify-content: center;
          align-items: center">
            <div style="text-align:center">
              <div>${name}</div>
              <div>1000</div>
            </div>
        </div>`,
        extData: {
          id: id
        }
      })
      marker.on('click', e => {
        this.map.setZoom(zoomLevel) //7. 11. 14
        this.map.setCenter(new AMap.LngLat(lng, lat))
      })
      return marker
    },

    setCarMarker(lng, lat, id) {
      let marker = new AMap.Marker({
        position: new AMap.LngLat(lng, lat),
        icon: 'http://192.168.200.248/files/f1.jpg',
        autoRotation: true,
        extData: {
          id: id
        }
      })

      marker.on('click', e => {
        // marker.stopMove() 这里不能暂停
        this.infoWindow.setContent(
          this.createInfoWindow(title, content.join('<br/>'))
        )
        this.infoWindow.open(this.map, e.target.getPosition())
      })

      return marker
    },

    createInfoWindow(title, content) {
      var info = document.createElement('div')

      // 定义中部内容
      var middle = document.createElement('div')
      middle.className = 'info-middle'
      middle.style.backgroundColor = 'white'
      middle.innerHTML = content
      info.appendChild(middle)

      // 定义底部内容
      var bottom = document.createElement('button')
      bottom.style.position = 'relative'
      bottom.style.top = '0px'
      bottom.style.margin = '0 auto'
      bottom.innerHTML = '按钮点击'
      info.appendChild(bottom)
      return info
    },

    //关闭信息窗体
    closeInfoWindow() {
      map.clearInfoWindow()
    },

    // 模拟异步请求数据
    fakeGetData() {
      this.data2 = this.data1
      // 下面的settimeout即模仿请求间隔时间，下面的data改变应该放在promise的then里
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.data1 = [
          {
            id: '1',
            pos: [118.8, 32.055203]
          },
          {
            id: '2',
            pos: [118.791072, 32.057385]
          },
          {
            id: '3',
            pos: [118.804634, 32.051274]
          },
          {
            id: '4',
            pos: [118.803089, 32.051056]
          }
          // {
          //   id: '5',
          //   pos: [116.47, 39.94]
          // }
        ]
        this.updateMarker()
      }, 2000)
    },

    // 经纬度计算角度
    // 这里还有点问题，方向的问题待定
    GetDistance(lat1, lng1, lat2, lng2) {
      let a = this.map.lnglatToPixel(new AMap.LngLat(lat1, lng1))
      let b = this.map.lnglatToPixel(new AMap.LngLat(lat2, lng2))
      let x = b.x - a.x
      let y = b.y - a.y
      let deg = (Math.atan(y / x) * 360) / (2 * Math.PI)
      if (x > 0 && y < 0) {
        // 第一象限
        deg = 180 - deg
      } else {
        deg = 270 - deg
      }
      return deg
    }
  }
}
</script>

<style lang="scss" scoped>
.map_container {
  // justify-content: center;
  // align-items: center
}
</style>
